package com.czf.personal.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.czf.common.entity.OtherSoftwareCore;
import com.czf.common.entity.RecordUserSoftScore;
import com.czf.common.mapper.OtherSoftwareCoreMapper;
import com.czf.common.mapper.RecordUserSoftScoreMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author zfChen
 * @create 2022/4/22 16:20
 */
@Service
public class SoftwareScoreServiceImpl {

    @Autowired
    private RecordUserSoftScoreMapper recordUserSoftScoreMapper;

    @Autowired
    private OtherSoftwareCoreMapper otherSoftwareCoreMapper;

    public Double select(OtherSoftwareCore otherSoftwareCore,Long userId){
        QueryWrapper<OtherSoftwareCore> wrapper = new QueryWrapper<>();
        wrapper.eq("telphone",otherSoftwareCore.getTelphone());
        wrapper.eq("software",otherSoftwareCore.getSoftware());
        OtherSoftwareCore softwareCore = otherSoftwareCoreMapper.selectOne(wrapper);
        if (ObjectUtils.isNotEmpty(softwareCore)) {
            Integer totalScore = softwareCore.getTotalScore();
            Integer score = softwareCore.getScore();

            BigDecimal b = new BigDecimal((float)score*5/totalScore);
            Double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();

            RecordUserSoftScore record = new RecordUserSoftScore();
            record.setUserId(userId);
            record.setSoftwareName(otherSoftwareCore.getSoftware());
            if (record.getSoftwareName().equals("mayihuabei")) {
                record.setReliability(3);
            } else if (record.getSoftwareName().equals("jingdongjinrong")){
                record.setReliability(2);
            }
            record.setScore(result.toString());


            QueryWrapper<RecordUserSoftScore> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            queryWrapper.eq("software_name",record.getSoftwareName());
            RecordUserSoftScore selectOne = recordUserSoftScoreMapper.selectOne(queryWrapper);
            if (ObjectUtils.isNotEmpty(selectOne)) {
                UpdateWrapper<RecordUserSoftScore> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("user_id",userId);
                updateWrapper.eq("software_name",record.getSoftwareName());
                recordUserSoftScoreMapper.update(record, updateWrapper);
                return result;
            }
            recordUserSoftScoreMapper.insert(record);
            return result;
        }
        return 0.0;
    }
}
